﻿using Microsoft.AspNetCore.Mvc;
using Zdap.Common;

namespace Datav.Web.Api.Controllers
{
    /// <summary>
    ///
    /// </summary>
    ///
    public class FileController : BaseController
    {
        /// <summary>
        /// 存储数据库文件和资源包文件的目录
        /// </summary>
        private readonly string _dbFileDirectory = AppContext.BaseDirectory + "data";
        private readonly string _resourceDirectory = AppContext.BaseDirectory + "Uploads";
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceFactory"></param>
        public FileController(IServiceFactory serviceFactory) : base(serviceFactory)
        {
        }
        /// <summary>
        /// 文件本地上传
        /// </summary>
        /// <param name="files">上传文件</param>
        /// <param name="UploadFolder">项目目录</param>
        /// <returns></returns>
        [HttpPost]
        public virtual Task<ResponseContext<string>> Upload(List<IFormFile> files, string UploadFolder = "")
        {
            var rest = new ResponseContext<string>();
            if (files == null || files.Count == 0)
                return Task.FromResult(rest.SetError("请上传文件"));

            string filePath;
            if (!string.IsNullOrEmpty(UploadFolder))
            {
                filePath = UploadFolder;
                if (!filePath.EndsWith("/") || !filePath.EndsWith("\\"))
                {
                    filePath += "/";
                }
            }
            else
            {
                filePath = $"Uploads/{UploadFolder}/Tables/{DateTime.Now.ToString("yyyMMddHHmmsss") + new Random().Next(1000, 9999)}/";
            }

            string fullPath = filePath;//.MapPath(true);
            int i = 0;
            try
            {
                if (!Directory.Exists(fullPath))
                    Directory.CreateDirectory(fullPath);
                for (i = 0; i < files.Count; i++)
                {
                    string fileName = files[i].FileName;
                    using (var stream = new FileStream(fullPath + fileName, FileMode.Create))
                    {
                        files[i].CopyTo(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(rest.SetError(ex.Message));
            }
            return Task.FromResult(rest.SetSuccess(filePath, "文件上传成功"));
        }

       }
}